package com.dly.hope.handler;

import com.dly.hope.constant.GlobalException;
import com.dly.hope.constant.HttpConstant;
import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
import org.springframework.http.HttpStatus;
import com.dly.hope.constant.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author linyu.dai
 * @project myserve
 * @description 全局异常处理拦截器
 * @creat 2022/8/27 14:39:43
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 拦截所有的异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<R<Void>> errorHandler(Exception e){

        if(e instanceof GlobalException){
           return ResponseEntity.ok(R.error((GlobalException) e));
        }

        if(e instanceof IllegalArgumentException){
           return  ResponseEntity.ok(R.error(HttpConstant.request_error, e.getMessage()));
        }

        log.error("{}",e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error(HttpConstant.server_error, e.getMessage()));
    }

}
